
#include "color.h"

	// converst an hsv value to rgb
int hsv2rgb (float h, float s, float v,
			 float* red, float* green, float* blue)
	// assumes h, s and v to be in the range of [0,1]
	// returns r, g, b in range of [0,1]
{
	float a, b, c, f;
	int i;

	if (s == 0)
	{
			// must be grayscale
		*red = v;
		*green = v;
		*blue = v;
	}
	else
	{
		h *= 6.0;
		i = (int)floor (h);
		f = h - i;
		a = v * (1 - s);
		b = v * (1 - s*f);
		c = v * (1 - s*(1-f));

		switch (i)
		{
		case 0:
			*red = v; *green = c; *blue = a;
			break;
		case 1:
			*red = b; *green = v; *blue = a;
			break;
		case 2:
			*red = a; *green = v; *blue = c;
			break;
		case 3:
			*red = a; *green = b; *blue = v;
			break;
		case 4:
			*red = c; *green = a; *blue = v;
			break;
		case 5:
			*red = v; *green = a; *blue = b;
			break;
		default:
			break;
		}
	}

	return 1;
}

	// returns the max of the two passed numbers
float MAX (float a, float b) {return a>b?a:b;}
	// returns the min of the two passed number
float MIN (float a, float b) {return a>b?b:a;}

int rgb2hsv (float r, float g, float b, float *h, float *s, float *v)
	// Assumes r, g, and b are in the range of [0,1]
	// Assumes h, s, v in the range of [0, 1]
{
	float min, max, delta;

	max = MAX (r, MAX (g,b));
	min = MIN (r, MIN(g,b));
	delta = max - min;
	*v = max;

	if (max != 0.0)
		*s = delta/max;
	else
		*s = 0.0;

	if (*s = 0.0)
	{
		*h = 0.0f;
	}
	else
	{
		if (r == max)
		{
			*h = (float)((g - b) / delta);
		}
		else
		{
			if (g == max)
			{
				*h = (float)(2.0 + (b - r) / delta);
			}
			else
			{
				if (b == max)
				{
					*h = (float)(4 + (r - g) / delta);
				}
			}
		}
		*h = (float)(*h * 60.0);

		if (*h < 0)
		{
			*h = *h + 360;
		}

		*h = *h / 360;
	}
	return 1;
}